package com.ruoyi.face.service;

import cn.hutool.core.collection.CollectionUtil;
import com.arcsoft.face.FaceInfo;
import com.arcsoft.face.toolkit.ImageFactory;
import com.arcsoft.face.toolkit.ImageInfo;
import com.ruoyi.face.dto.FaceRecognitionResDTO;
import com.ruoyi.face.entity.UserCompareInfo;
import com.ruoyi.face.util.Base64Util;
import com.ruoyi.face.util.UserRedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class FaceLoginService {
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private UserRedisCache userRedisCache;

    public FaceRecognitionResDTO facelogin(String image) {

        FaceRecognitionResDTO faceRecognitionRes = new FaceRecognitionResDTO();
        faceRecognitionRes.setSimilar(0);
        byte[] bytes = Base64Util.base64ToBytes(image);
        ImageInfo rgbData = ImageFactory.getRGBData(bytes);
        List<FaceInfo> faceInfoList = faceEngineService.detectFaces(rgbData);
        if (CollectionUtil.isNotEmpty(faceInfoList)) {
            for (FaceInfo faceInfo : faceInfoList) {
                FaceRecognitionResDTO faceRecognitionResDTO = new FaceRecognitionResDTO();
                faceRecognitionResDTO.setRect(faceInfo.getRect());
                byte[] feature = faceEngineService.extractFaceFeature(rgbData, faceInfo);
                if (feature != null) {
                    List<UserCompareInfo> userCompareInfos = faceEngineService.faceRecognition(feature, userRedisCache.getUserList(), 0.5f);
                    if (CollectionUtil.isNotEmpty(userCompareInfos)) {
                        faceRecognitionResDTO.setName(userCompareInfos.get(0).getName());
                        faceRecognitionResDTO.setSimilar(userCompareInfos.get(0).getSimilar());
                        if (userCompareInfos.get(0).getSimilar() > faceRecognitionRes.getSimilar()) {
                            faceRecognitionRes = faceRecognitionResDTO;
                        }
                    }

                }
            }

        }


        return faceRecognitionRes;
    }
}
